import {messages} from "share/common";
import expenseService from '../../my-account/expense.service';
import {
  ZoomIn,
  RotateLeft,
  RotateRight,
  Download,
  List,
  LeftArrow,
  RightArrow,
  ZoomOut
} from '../svg-component/index';
import { getAttachment }  from 'containers/expense/util';

export default {
  utils() {
    const attachmentUtils = [
      {
        type: 'zoom-in',
        name: messages('expense-1.key678')/*放大*/
      },
      {
        type: 'rotate-left',
        name: messages('expense-1.key679')/*左转90°*/
      },
      {
        type: 'rotate-right',
        name: messages('expense-1.key680')/*右转90°*/
      },
      {
        type: 'download',
        name: messages('expense-1.key593')/*下载*/
      },
      {
        type: 'check',
        name: messages('expense-1.key681')/*核对*/
      },
      {
        type: 'line',
        name: messages('expense-1.key682')/*竖线*/
      },
      {
        type: 'list',
        name: messages('expense-1.key683')/*切换列表*/
      }
    ];

    const gestures = [
      {
        type: 'left',
        component: LeftArrow,
      },
      {
        type: 'right',
        component: RightArrow
      }
    ];

    const components = {
      'zoom-in': ZoomIn,
      'rotate-left': RotateLeft,
      'rotate-right': RotateRight,
      'download': Download,
      'list': List,
      'zoom-out': ZoomOut
    };
    return { gestures, attachmentUtils, components };
  },
  async initData(expense, context) {
    const { attachments: attachment, receiptList: invoice, bankTransactionDetails: business } = expense;
    let currentFlag,
      mergeAdjuncts = [],
      receiptLabels = [],
      currentAttachment = {},
      currentAdjunct = {},
      adjuncts = { invoice, attachment, business },
      adjuncts_map = {
        invoice: messages('expense-1.key684')/*发票*/,
        attachment: messages('common.attachments')/*附件*/,
        business: messages('expense-1.key313')/*消费账单*/
      };

    invoice && invoice[0] && invoice.forEach(item => {
      item.receiptLabels.forEach(label => {
        !receiptLabels.some(item => item.type === label.type) && receiptLabels.push(label);
      });
    });

    Object.keys(adjuncts)
      .forEach(item => {
        if (adjuncts[item] && adjuncts[item][0]) {
          mergeAdjuncts.push({
            name: adjuncts_map[item],
            type: item,
            body: [...adjuncts[item]]
          });
        }
      });

    if (mergeAdjuncts[0]) {
      currentAdjunct = mergeAdjuncts[0].body[0];
      currentAttachment = getAttachment(currentAdjunct)
      currentFlag = mergeAdjuncts[0].type;
    }

    await context.setState({
      currentFlag,
      receiptLabels,
      mergeAdjuncts,
      currentAdjunct,
      currentAttachment,
      currentAttachmentIndex: 0
    });
  },
  async initReceiptChangeData(expense, context) {
    const { receiptList = [] } = expense;
    let promise_map = [],
      receiptChanges = {},
    receiptLabelsDesc = {};
    receiptList.forEach(item => {
      const { id, checkResult, pdfDamaged, invoiceOID } = item;
      receiptLabelsDesc[id] = [...item.receiptLabels.filter(item => item.level !== 'INFO')];
      item.receiptLabels
        .some(item =>
          (['MODIFY_RECEIPT', 'INSP_FAILED', 'MISMATCHED_INV', 'NON_EMPLOYEES', 'UNCLEAR_COMPANY'].indexOf(item.type || item.code) !== -1 ||
            pdfDamaged === true)) &&
            promise_map.push(this.getReceiptChangeData({ id, checkResult, pdfDamaged, invoiceOID }));
    });
    await Promise.all(promise_map)
      .then(changeData => { // 发票改动后端返回数据结构与新版报销单详情设计严重不符，后续最好优化 复杂度太高
        let i = 0;
        while (i < changeData.length) {
          const { receiptId } = changeData[i];
          let currentLabels = receiptLabelsDesc[receiptId];
          changeData[i].data.forEach(item => {
            currentLabels.some(label => {
              if (label.type === item.type) {
                label.moreDesc = item.description;
                return true;
              }
            });
            if (item.type === 'MODIFY_RECEIPT') {
              receiptChanges[receiptId] = {};
              item.history.forEach(histories => {
                const { createdDate, operatorName, operatorType } = histories;
                histories.detailInfo.forEach(history => {
                  if (history.propertyKey) {
                    !receiptChanges[receiptId][history.propertyKey] && (receiptChanges[receiptId][history.propertyKey] = []);
                    receiptChanges[receiptId][history.propertyKey].push({
                      ...history,
                      createdDate,
                      operatorName,
                      operatorType
                    });
                  }
                });
              });
            }
          });
          i++;
        }
        context.setState({ receiptChanges, receiptLabelsDesc });
      });
  },
  async getReceiptChangeData(params) {
    const res = await expenseService.getInvoiceChangeRecordV2(params);
    return { data: res.data, receiptId: params.id };
  },
  resetData(expense, labelFilter, mergeAdjuncts) {
    const { receiptList } = expense;
    mergeAdjuncts.forEach(item => {
      item.type === 'invoice' && (item.body = receiptList.filter(item => !labelFilter[0] || item.receiptLabels.some(item => labelFilter.includes(item.type))));
    });
  }
};
